<?php
/**
 * Service of Category
 *
 * @author fsqijy
 */

require_once BaseUtil::getModulePath("base")  .  '/services/BaseService.php';
require_once BaseUtil::getModulePath("inventory")  .  '/models/CategoryDao.php';
require_once BaseUtil::getModulePath("metadata")  .  '/models/MetadataSetDao.php';
require_once BaseUtil::getModulePath("systemlog")  .  '/services/SystemLogService.php';

class CategoryService extends BaseService {

    private $categoryDao;

    private $metadataSetDao;

    //private $categoryResult = array(0=>"Root");

    public function __construct () {
        parent::__construct();
        $this->categoryDao = new CategoryDao();
        $this->categoryDao->setDb($this->db);
        $this->metadataSetDao = new MetadataSetDao();
        $this->metadataSetDao->setDb($this->db);
    }
    public function getAllCategoriesXml() {
        $parentId = 0;
        $result = $this->getAllCategories($parentId);
        $categoryXml = '<tree id="0">';
        $categoryXml .= '<item text="Root" id="-1" >';
        $categoryXml .= $result;
        $categoryXml .= '</item>';
        $categoryXml .= '</tree>';
        return $categoryXml;
    }

    private function getAllCategories($parentId = 0) {
        $categoryXml = '';
        $categories = $this->categoryDao->getCategoryByParentId($parentId);
        if(!empty($categories)) {
            foreach($categories as $category) {
                $categoryId = $category['id'];
                $categorySName = $category['short_name'];
                $categoryXml .= '<item text="'. htmlspecialchars($category['short_name']) .'('. $category['id'] .')" id="'. $category['id'] .'" >';
                $categoryXml .= $this->getAllCategories($categoryId);
                $categoryXml .= '</item>';
            }
        }
        return $categoryXml;
    }

    public function addCategory($category) {
        $this->categoryDao->insertData($category);
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('ADDCG',$loginUser['uname'], $category);
    }

    public function getCategoryById($id) {
        return $this->categoryDao->getByCol("id", $id);
    }

    public function updateCategory($categoryId,$category) {
        $this->categoryDao->updateCategory($categoryId, $category);
        //update log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('EDITCG',$loginUser['uname'], $category,$categoryId);        
    }

    public function getMetadataSet() {
        $result = array();
        $result["0"] = "-None-";
        $metadataSets = $this->metadataSetDao->getMetadataSet();
        foreach($metadataSets as $metadataSet){
            $result[$metadataSet['id']] = $metadataSet['title'];
        }
        return $result;
    }
}
